<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 模拟API请求
const fetchStores = async () => {
  return [
    { id: 1, name: '蜗牛智慧餐厅-总店', address: '北京市朝阳区建国路88号', phone: '010-88889999', status: 1 },
    { id: 2, name: '蜗牛智慧餐厅-分店1', address: '北京市海淀区中关村大街1号', phone: '010-66667777', status: 1 },
    { id: 3, name: '蜗牛智慧餐厅-分店2', address: '上海市浦东新区陆家嘴环路100号', phone: '021-55556666', status: 1 },
    { id: 4, name: '蜗牛智慧餐厅-分店3', address: '广州市天河区天河路200号', phone: '020-33334444', status: 1 },
    { id: 5, name: '蜗牛智慧餐厅-分店4', address: '深圳市南山区科技园路300号', phone: '0755-22223333', status: 0 }
  ]
}

const fetchPaymentMethods = async () => {
  return [
    { id: 1, name: '支付宝', code: 'alipay', icon: '/icons/alipay.png', sort: 1, status: 1 },
    { id: 2, name: '微信支付', code: 'wechat', icon: '/icons/wechat.png', sort: 2, status: 1 },
    { id: 3, name: '会员卡', code: 'member_card', icon: '/icons/member.png', sort: 3, status: 1 },
    { id: 4, name: '银行卡', code: 'bank_card', icon: '/icons/bank.png', sort: 4, status: 1 },
    { id: 5, name: '现金', code: 'cash', icon: '/icons/cash.png', sort: 5, status: 1 }
  ]
}

const fetchStorePaymentMethods = async (storeId) => {
  // 模拟API返回数据
  const allData = {
    1: [
      { id: 1, store_id: 1, payment_method_id: 1, status: 1, config: '{"appId":"2021000123456789","privateKey":"MIIEvA...","publicKey":"MIIBIj..."}' },
      { id: 2, store_id: 1, payment_method_id: 2, status: 1, config: '{"appId":"wx1234567890abcdef","mchId":"123456789","apiKey":"abcdefghijklmnopqrstuvwxyz123456"}' },
      { id: 3, store_id: 1, payment_method_id: 3, status: 1, config: '{"cardPrefix":"SN","pointsRate":1}' },
      { id: 4, store_id: 1, payment_method_id: 4, status: 1, config: '{"bankName":"中国银行","accountName":"蜗牛智慧餐厅","accountNumber":"1234567890123456"}' },
      { id: 5, store_id: 1, payment_method_id: 5, status: 1, config: '{"giveChange":true,"maxAmount":10000,"cashierConfirm":true}' }
    ],
    2: [
      { id: 6, store_id: 2, payment_method_id: 1, status: 1, config: '{"appId":"2021000123456789","privateKey":"MIIEvA...","publicKey":"MIIBIj..."}' },
      { id: 7, store_id: 2, payment_method_id: 2, status: 1, config: '{"appId":"wx1234567890abcdef","mchId":"123456789","apiKey":"abcdefghijklmnopqrstuvwxyz123456"}' },
      { id: 8, store_id: 2, payment_method_id: 3, status: 0, config: '{"cardPrefix":"SN","pointsRate":1}' },
      { id: 9, store_id: 2, payment_method_id: 5, status: 1, config: '{"giveChange":false,"maxAmount":5000,"cashierConfirm":false}' }
    ],
    3: [
      { id: 10, store_id: 3, payment_method_id: 1, status: 1, config: '{"appId":"2021000123456789","privateKey":"MIIEvA...","publicKey":"MIIBIj..."}' },
      { id: 11, store_id: 3, payment_method_id: 2, status: 1, config: '{"appId":"wx1234567890abcdef","mchId":"123456789,"apiKey":"abcdefghijklmnopqrstuvwxyz123456"}' },
      { id: 12, store_id: 3, payment_method_id: 3, status: 1, config: '{"cardPrefix":"SN","pointsRate":1.2}' },
      { id: 13, store_id: 3, payment_method_id: 5, status: 1, config: '{"giveChange":true,"maxAmount":2000,"cashierConfirm":true}' }
    ],
    4: [
      { id: 14, store_id: 4, payment_method_id: 1, status: 1, config: '{"appId":"2021000123456789","privateKey":"MIIEvA...","publicKey":"MIIBIj..."}' },
      { id: 15, store_id: 4, payment_method_id: 2, status: 1, config: '{"appId":"wx1234567890abcdef","mchId":"123456789","apiKey":"abcdefghijklmnopqrstuvwxyz123456"}' },
      { id: 16, store_id: 4, payment_method_id: 5, status: 1, config: '{"giveChange":true,"maxAmount":3000,"cashierConfirm":false}' }
    ],
    5: [
      { id: 17, store_id: 5, payment_method_id: 1, status: 1, config: '{"appId":"2021000123456789","privateKey":"MIIEvA...","publicKey":"MIIBIj..."}' },
      { id: 18, store_id: 5, payment_method_id: 2, status: 1, config: '{"appId":"wx1234567890abcdef","mchId":"123456789","apiKey":"abcdefghijklmnopqrstuvwxyz123456"}' },
      { id: 19, store_id: 5, payment_method_id: 5, status: 1, config: '{"giveChange":false,"maxAmount":1000,"cashierConfirm":true}' }
    ]
  }

  return allData[storeId] || []
}

// 数据
const stores = ref([])
const paymentMethods = ref([])
const selectedStore = ref(null)
const configDialogVisible = ref(false)
const currentPaymentMethod = ref({})
const paymentConfig = ref({})

// 初始化加载门店列表
onMounted(async () => {
  stores.value = await fetchStores()
  if (stores.value.length > 0) {
    selectedStore.value = stores.value[0].id
    await loadPaymentMethods()
  }
})

// 加载支付方式
const loadPaymentMethods = async () => {
  if (!selectedStore.value) return

  const allMethods = await fetchPaymentMethods()
  const storeMethods = await fetchStorePaymentMethods(selectedStore.value)

  paymentMethods.value = allMethods.map(method => {
    const storeMethod = storeMethods.find(m => m.payment_method_id === method.id)
    return {
      ...method,
      status: storeMethod ? storeMethod.status : 0,
      storeMethodId: storeMethod ? storeMethod.id : null,
      config: storeMethod ? JSON.parse(storeMethod.config || '{}') : {}
    }
  })
}

// 更新支付方式状态
const updatePaymentMethodStatus = async (row) => {
  try {
    // 这里应该是调用API更新状态
    ElMessage.success(`${row.name}状态已更新`)
  } catch (error) {
    ElMessage.error('更新失败')
    // 恢复原来的状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 显示配置对话框
const showConfigDialog = (method) => {
  currentPaymentMethod.value = method
  paymentConfig.value = { ...method.config }
  configDialogVisible.value = true
}

// 保存支付配置
const savePaymentConfig = async () => {
  try {
    // 这里应该是调用API保存配置
    const methodIndex = paymentMethods.value.findIndex(m => m.id === currentPaymentMethod.value.id)
    if (methodIndex !== -1) {
      paymentMethods.value[methodIndex].config = { ...paymentConfig.value }
    }
    ElMessage.success('配置保存成功')
    configDialogVisible.value = false
  } catch (error) {
    ElMessage.error('保存失败')
  }
}
</script>


<template>
  <div class="payment-settings-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>支付设置</h2>
        </div>
      </template>

      <!-- 门店选择 - 修改了宽度 -->
      <div class="store-select">
        <el-form label-width="120px">
          <el-form-item label="请选择门店">
            <el-select
                v-model="selectedStore"
                placeholder="请选择门店"
                @change="loadPaymentMethods"
                style="width: 300px"
            >
            <el-option
                v-for="store in stores"
                :key="store.id"
                :label="store.name"
                :value="store.id"
            />
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <!-- 支付方式表格 -->
      <el-table :data="paymentMethods" border style="width: 100%">
        <el-table-column prop="name" label="支付方式" width="180" />
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-switch
                v-model="row.status"
                :active-value="1"
                :inactive-value="0"
                @change="updatePaymentMethodStatus(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <!-- 为现金支付也添加了配置按钮 -->
            <el-button
                type="primary"
                size="small"
                @click="showConfigDialog(row)"
            >
              配置
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 支付配置对话框 -->
    <el-dialog
        v-model="configDialogVisible"
        :title="`${currentPaymentMethod.name}配置`"
        width="50%"
    >
      <el-form :model="paymentConfig" label-width="120px">
        <template v-if="currentPaymentMethod.code === 'alipay'">
          <el-form-item label="APP ID">
            <el-input v-model="paymentConfig.appId" />
          </el-form-item>
          <el-form-item label="商户私钥">
            <el-input v-model="paymentConfig.privateKey" type="textarea" rows="3" />
          </el-form-item>
          <el-form-item label="支付宝公钥">
            <el-input v-model="paymentConfig.publicKey" type="textarea" rows="3" />
          </el-form-item>
        </template>

        <template v-else-if="currentPaymentMethod.code === 'wechat'">
          <el-form-item label="APP ID">
            <el-input v-model="paymentConfig.appId" />
          </el-form-item>
          <el-form-item label="商户号">
            <el-input v-model="paymentConfig.mchId" />
          </el-form-item>
          <el-form-item label="API密钥">
            <el-input v-model="paymentConfig.apiKey" />
          </el-form-item>
        </template>

        <template v-else-if="currentPaymentMethod.code === 'member_card'">
          <el-form-item label="会员卡前缀">
            <el-input v-model="paymentConfig.cardPrefix" />
          </el-form-item>
          <el-form-item label="积分兑换比例">
            <el-input-number v-model="paymentConfig.pointsRate" :min="0" :step="0.1" />
            <span class="form-tip">1元 = {{ paymentConfig.pointsRate || 0 }}积分</span>
          </el-form-item>
        </template>

        <template v-else-if="currentPaymentMethod.code === 'bank_card'">
          <el-form-item label="银行名称">
            <el-input v-model="paymentConfig.bankName" />
          </el-form-item>
          <el-form-item label="账户名称">
            <el-input v-model="paymentConfig.accountName" />
          </el-form-item>
          <el-form-item label="账号">
            <el-input v-model="paymentConfig.accountNumber" />
          </el-form-item>
        </template>

        <!-- 现金支付配置项 -->
        <template v-else-if="currentPaymentMethod.code === 'cash'">
          <el-form-item label="是否找零">
            <el-switch v-model="paymentConfig.giveChange" />
          </el-form-item>
          <el-form-item label="最大现金金额">
            <el-input-number v-model="paymentConfig.maxAmount" :min="0" :step="100" />
            <span class="form-tip">设置最大接受的现金金额</span>
          </el-form-item>
          <el-form-item label="收银员确认">
            <el-switch v-model="paymentConfig.cashierConfirm" />
            <span class="form-tip">启用后需要收银员确认收款</span>
          </el-form-item>
        </template>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="configDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePaymentConfig">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.payment-settings-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.store-select {
  margin-bottom: 20px;
}

.form-tip {
  margin-left: 10px;
  font-size: 12px;
  color: #999;
}
</style>